package com.javaDemo.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JoinExample {
    public static void main(String[] args) {
        Lock lock =new ReentrantLock();
        ExecutorService executorService = Executors.newCachedThreadPool();
        JoinExample example = new JoinExample();
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.execute(() -> {
                // lock.lock();
                // try {
                //     example.test();
                // } finally {
                //     lock.unlock();
                // }

                if(lock.tryLock()) {
                    try{
                        //处理任务
                        example.test();
                    }catch(Exception ex){

                    }finally{
                        lock.unlock();   //释放锁
                    }
                }

            });

        }
    }

    public void test() {
        A a = new A();
        B b = new B(a);
        b.start();
        a.start();
    }

    private class A extends Thread {
        @Override
        public void run() {
            System.out.println("A");
        }
    }

    private class B extends Thread {

        private A a;

        B(A a) {
            this.a = a;
        }

        @Override
        public void run() {
            try {
                a.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B-----");
        }
    }
}